package com.xuexiang.xuidemo.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.view.ViewCompat;

import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xuidemo.entity.Decision;

public class Sector extends View {

    private static final int ONE_WHEEL_TIME = 500;
    int length = 2;
    int colors[] = {
            Color.parseColor("#2979FF"), Color.parseColor("#C2185B"),
            Color.parseColor("#009688"), Color.parseColor("#FF8F00")
    };
    float angles[] = {
            160f, 200f
    };
    String text[] = {
            "1", "2"
    };
    float startAngle = 0f;
    float RADIUS = DensityUtils.dp2px(getContext(), 150);
    RectF mBounds = new RectF();
    Paint mPaint = null;
    Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public Sector(Context context) {
        super(context);
    }

    public Sector(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public Sector(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public Sector(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBounds.set(w / 2 - RADIUS, h / 2 - RADIUS, w / 2 + RADIUS, h / 2 + RADIUS);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAlpha(255);
        float angle = startAngle;
        for (int i = 0; i < length; i++) {
            mPaint.setColor(colors[i % colors.length]);
            canvas.drawArc(mBounds, angle, angles[i], true, mPaint);
            angle += angles[i];
        }
        angle = startAngle;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.WHITE);
        mPaint.setStrokeWidth(10);
        for (int i = 0; i < length; i++) {
            canvas.drawArc(mBounds, angle, angles[i], true, mPaint);
            angle += angles[i];
        }
        angle = startAngle;
        //mPaint.setColor(Color.rgb(0,0,0));
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(DensityUtils.dp2px(getContext(), 22));
        for (int i = 0; i < length; i++) {
            drawText(angle, angles[i], text[i], (int) RADIUS * 2, mTextPaint, canvas, mBounds);
            angle += angles[i];
        }
        Paint qPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        qPaint.setAlpha(255);
        qPaint.setColor(Color.WHITE);
        int re = DensityUtils.dp2px(getContext(), 100);
        //canvas.drawArc(new RectF(mBounds.left+re,mBounds.top+re,mBounds.right-re,mBounds.bottom-re),0,360,true,qPaint);
        int ret = DensityUtils.dp2px(getContext(), 70);
        canvas.drawArc(new RectF(mBounds.left + re, mBounds.top + re - ret, mBounds.right - re, mBounds.bottom - re - ret), 60, 60, true, qPaint);
    }

    private void drawText(float startAngle, float verPanRadius, String string, int mRadius, Paint mTextPaint, Canvas mCanvas, RectF mRange) {
        Path path = new Path();

        path.addArc(mRange, startAngle, verPanRadius);
        float textWidth = mTextPaint.measureText(string);

        //圆弧的水平偏移
        float hOffset = (float) (mRadius * Math.PI * verPanRadius / 360 / 2 - textWidth / 2);
        //圆弧的垂直偏移
        float vOffset = mRadius / 2 / 5;

        mCanvas.drawTextOnPath(string, path, hOffset, vOffset, mTextPaint);
    }

    public void set(Decision decision) {
        length = decision.getResults().size();
        angles = new float[length];
        text = new String[length];
        float sum = 0;
        for (int i = 0; i < length; i++) {
            text[i] = decision.getResults().get(i);
            angles[i] = (float) decision.getWeights().get(i);
            sum += angles[i];
        }
        angles[0] = 360f;
        for (int i = 1; i < length; i++) {
            angles[i] = angles[i] / sum * 360f;
            angles[0] -= angles[i];
        }
        invalidate();
    }

    public void setColors(int[] newcolors) {
        this.colors = newcolors;
        invalidate();
    }

    public void setStartAngle(float stang) {
        startAngle = stang;
        invalidate();
        //UpdateWindow();
    }

    public void startRotate(int angle) {

        //Rotate lap.
        int lap = (int) (Math.random() * 12) + 4;

        //All of the rotate angle.
        int increaseDegree = lap * 360 + angle;
        long time = (lap + angle / 360) * ONE_WHEEL_TIME;
        int DesRotate = (int) (increaseDegree + startAngle);

        ValueAnimator animtor = ValueAnimator.ofInt((int) startAngle, DesRotate);
        animtor.setInterpolator(new AccelerateDecelerateInterpolator());
        animtor.setDuration(time);
        animtor.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int updateValue = (int) animation.getAnimatedValue();
                startAngle = (updateValue % 360 + 360) % 360;
                ViewCompat.postInvalidateOnAnimation(com.xuexiang.xuidemo.view.Sector.this);
            }

        });
        animtor.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                getAnimationEndListener().endAnimation();
            }
        });

        /*
        animtor.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if(((LuckPanLayout)getParent()).getAnimationEndListener()!= null)
                {
                    ((LuckPanLayout)getParent()).setStartBtnEnable(true);
                    ((LuckPanLayout)getParent()).setDelayTime(LuckPanLayout.DEFAULT_TIME_PERIOD);
                    ((LuckPanLayout)getParent()).getAnimationEndListener().endAnimation(queryPosition());
                }
            }
        });*/
        animtor.start();
    }

    public int queryPosition() {
        float nowAngle = (startAngle % 360 + 360) % 360;
        int pos = 0;
        float sum = 0;
        if (nowAngle > 270)
            sum = 270 + 360 - nowAngle;
        else sum = 270 - nowAngle;
        for (pos = 0; pos < length; pos++) {
            if (sum < angles[pos]) break;
            sum -= angles[pos];
        }
        return pos;
    }

    public interface AnimationEndListener {
        void endAnimation();
    }

    AnimationEndListener l;

    public void setAnimationEndListener(AnimationEndListener l) {
        this.l = l;
    }

    public AnimationEndListener getAnimationEndListener() {
        return l;
    }
}
